package Controller.AdminUser;

import Models.dao.AdminUserDao;
import Models.enity.AdminUser;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/login")
public class LoginController extends HttpServlet {
    private static String PublicPath = "/WEB-INF/views";
    private static AdminUserDao userDao = new AdminUserDao();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher(PublicPath + "/admin_user/login.jsp").forward(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        AdminUser user = userDao.findByUsername(username);
        if (user !=null && user.getPassword().equals(password)){
            HttpSession session = req.getSession();
            session.setAttribute("user",user);
            session.setAttribute("user_pass",user.getPassword());
            session.setAttribute("user_id",user.getId());
            resp.sendRedirect("/index");
            return;
        }else {
            req.setAttribute("username",username);
            req.setAttribute("error",1);
            req.getRequestDispatcher(PublicPath + "/admin_user/login.jsp").forward(req,resp);
        }
    }
}
